package com.xiepei.day01;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 演示普通数组与 ArrayList 在“添加元素”场景下的差异。
 */
public class Lesson04_ArrayVsArrayList {

    public static void main(String[] args) {
        demoPlainArray();
        System.out.println();
        demoArrayList();
        System.out.println();
        demoFixedSizeList();
        newArr();
    }

    public static void newArr(){
        List<String> list = new ArrayList<>();
    }

    private static void demoPlainArray() {
        String[] fruitsArray = {"苹果", "香蕉", "橙子"};
        System.out.println("=== 普通数组 ===");
        System.out.println("初始数组：" + Arrays.toString(fruitsArray));

        // fruitsArray.add("葡萄"); // 编译器直接报错：Cannot resolve method 'add'

        fruitsArray = append(fruitsArray, "葡萄");
        System.out.println("通过扩容复制后得到的新数组：" + Arrays.toString(fruitsArray));
    }

    private static void demoArrayList() {
        List<String> fruitsList = new ArrayList<>(Arrays.asList("苹果", "香蕉", "橙子"));
        System.out.println("=== ArrayList ===");
        System.out.println("初始列表：" + fruitsList);

        fruitsList.add("葡萄");
        System.out.println("直接 add 后的列表：" + fruitsList);
    }

    private static void demoFixedSizeList() {
        List<String> fixed = Arrays.asList("苹果", "香蕉", "橙子");
        System.out.println("=== Arrays.asList 直接返回的列表 ===");
        System.out.println("初始列表：" + fixed);
        try {
            fixed.add("葡萄"); // 运行期会抛 UnsupportedOperationException
        } catch (UnsupportedOperationException ex) {
            System.out.println("尝试 add 时抛出异常：" + ex);
        }
    }

    private static String[] append(String[] source, String element) {
        String[] result = Arrays.copyOf(source, source.length + 1);
        result[result.length - 1] = element;
        return result;
    }
}

